package com.yanguilai.rabbitmqexchange;

import com.rabbitmq.client.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

@SpringBootApplication
public class RabbitmqExchangeApplication {

    //    private final static String EXCHANGE_NAME = "direct_logs";
    private final static String EXCHANGE_NAME = "topic_logs";
    private final static String[] facilities = {"formal", "mini", "last"};
    private final static String[] severities = {"info", "debug", "error"};

    private static ConnectionFactory factory;

    static {
        factory = new ConnectionFactory();
        factory.setHost("c7formal");
    }

    public static void main(String[] args) {
        SpringApplication.run(RabbitmqExchangeApplication.class, args);

        try {
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();
//            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);
            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
            String queueName = channel.queueDeclare().getQueue();

            if (args.length < 1) {
                System.err.println("Usage: ReceiveLogsTopic [binding_key]...");
                System.exit(1);
            }

            for (String arg : args) {
                if (arg.startsWith("--")) {
                    continue;
                }
                channel.queueBind(queueName, EXCHANGE_NAME, arg);
            }
            System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

            DeliverCallback callback = (tag, delivery) -> {
                String msg = new String(delivery.getBody(), StandardCharsets.UTF_8);
                System.out.println(" [x] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + msg + "'");
            };

            channel.basicConsume(queueName, true, callback, tag -> {});

        } catch (TimeoutException | IOException e) {
            e.printStackTrace();
        }
    }


}
